package tech.kpretty.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class Demo {
    private final List<String> list = new ArrayList<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();


    public void read() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读");
            System.out.println(list);
            System.out.println(Thread.currentThread().getName() + "读完了");
        } finally {
            readLock.unlock();
        }
    }

    public void write() {
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在写");
            list.add(UUID.randomUUID().toString().substring(0, 5));
            System.out.println(Thread.currentThread().getName() + "写完了");
        } finally {
            writeLock.unlock();
        }

    }
}

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        Demo demo = new Demo();
        for (int i = 0; i < 100; i++) {
            new Thread(demo::write, i + "").start();
        }

        for (int i = 0; i < 100; i++) {
            new Thread(demo::read, i + "").start();
        }
    }
}
